package edu.cuit.campus.web.controller;

import edu.cuit.campus.common.Result;
import edu.cuit.campus.po.Company;
import edu.cuit.campus.service.CompanyService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * GET:
 *    http://localhost/companies/:id   获取指定id的企业信息
 *    http://localhost/companies       获取所有的企业信息
 *          ?index=1&size=5 过滤信息
 * POST:
 *    http://localhost/companies       创建企业信息
 *
 * PUT:
 *    http://localhost/companies/:id   根据id修改企业信息
 *
 * DELETE
 *    http://localhost/companies/:id   根据id删除企业信息
 *
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/8/15 11:28
 */
@RestController // @ResponseBody + @Controller
@RequestMapping("/companies")
public class CompanyRestController {
    @Resource private CompanyService service;
    //http://localhost/companies/:id   获取指定id的企业信息
    //@RequestMapping(path = "/{id}", method = RequestMethod.GET)
    @GetMapping("/{id}")
    //@ResponseBody
    public Result findById(@PathVariable Integer id){
        var company = service.findById(id);
        return company == null ? Result.fail("企业不存在") : Result.ok(company);
    }

    //http://localhost/companies  获取所有的企业信息
    //@RequestMapping(method = RequestMethod.GET)
    @GetMapping
    //@ResponseBody
    public Result list(@RequestParam(name = "index", defaultValue = "1") int pageIndex,
                       @RequestParam(name = "size", defaultValue = "6") int pageSize){
        return Result.ok(service.list(pageIndex, pageSize));
    }

    //@RequestMapping(method = RequestMethod.POST)
    @PostMapping
    //@ResponseBody
    public Result save(@RequestBody Company company){
        var id = service.save(company);
        return id != null ? Result.ok() : Result.fail();
    }

    // http://localhost/companies/:id
    //@RequestMapping(path = "/{id}", method = RequestMethod.PUT)
    @PutMapping("/{id}")
    //@ResponseBody
    public Result edit(@PathVariable Integer id, @RequestBody Company company){
        company.setId(id);
        service.updateById(company);
        return Result.ok();
    }

    // http://localhost/companies/:id
    //@RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
    @DeleteMapping("/{id}")
    //@ResponseBody
    public Result deleteById(@PathVariable Integer id){
        service.removeById(id);
        return Result.ok();
    }
}
